package mn.idax.exchange.otc.task;

import com.alibaba.fastjson.JSON;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.dangdang.elasticjob.lite.annotation.ElasticSimpleJob;
import mn.idax.exchange.otc.config.AdProducter;
import mn.idax.exchange.otc.entity.Account;
import mn.idax.exchange.otc.entity.OTCAds;
import mn.idax.exchange.otc.entity.OTCAdsExample;
import mn.idax.exchange.otc.enums.AdEnum;
import mn.idax.exchange.otc.enums.MessageNotifyEnum;
import mn.idax.exchange.otc.mapper.OTCAdsMapper;
import mn.idax.exchange.otc.service.AccountService;
import mn.idax.exchange.otc.service.OTCAdsService;
import mn.idax.exchange.otc.util.DateUtils;
import mn.idax.exchange.otc.util.LogUtils;
import mn.idax.exchange.otc.util.MessageNotifyUtils;
import mn.idax.exchange.otc.vo.FloatingPriceDTO;
import mn.idax.exchange.otc.vo.OTCAutoDownAdDTO;
import mn.idax.exchange.otc.vo.SyncAdInMemory;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Auther: dison
 * @Date: 2018/9/28 14:07
 * @Description:
 */
@ElasticSimpleJob(cron = "0/5 * * * * ?")
@Component
public class AdvertisingSoldOutJob implements SimpleJob {

    @Autowired
    private OTCAdsService otcAdsService;

    @Autowired
    private OTCAdsMapper otcAdsMapper;

    @Autowired
    private AccountService accountService;

    @Autowired
    private AdProducter adProducter;

    @Override
    public void execute(ShardingContext shardingContext) {

        int total = 0;

        // 查询所有正在上架的广告
        OTCAdsExample otcAdsExample = new OTCAdsExample();
        otcAdsExample.createCriteria()
                .andTypeEqualTo(AdEnum.type_sell.getCode())
                .andStateEqualTo(AdEnum.state_up.getCode());

        List<OTCAds> otcAds = otcAdsMapper.selectByExample(otcAdsExample);

        try {
            // 循环广告
            for (OTCAds otcAd : otcAds) {
                // 查询发布者余额是否足够
                Account account = accountService.getAccountByCoinIdAndUserId(otcAd.getPublisherid(), otcAd.getPairid());
                FloatingPriceDTO floatingPriceDTO = otcAdsService.floatingAdsPriceConvert(new FloatingPriceDTO(otcAd.getType(), otcAd.getMinprice(), otcAd.getMaxprice(),
                        otcAd.getUnit(), otcAd.getExchange(), otcAd.getPairname(), otcAd.getPrice(), otcAd.getFloatingrate()));
                // 可用余额*广告价格 < 广告最小限购
                if (account.getAvailableamount().multiply(floatingPriceDTO.getPrice()).compareTo(otcAd.getMinamount()) == -1) {

                    OTCAutoDownAdDTO otcAutoDownAdDTO = OTCAutoDownAdDTO.builder()
                            .updateTime(DateUtils.getUTCNow())
                            .state(AdEnum.state_down.getCode())
                            .id(otcAd.getId())
                            .build();

                    //更新成功
                    if (otcAdsService.updateStateOTCAdsById(otcAutoDownAdDTO) == 1) {

                        //将广告从内存中移除
                        adProducter.sendDownAdMessage(JSON.toJSONString(new SyncAdInMemory(otcAd.getId(),otcAd.getPublisherid())));
                        LogUtils.info(this.getClass(), "AdvertisingJobDownAd adId : " + otcAd.getId() + "minamount: " + otcAd.getMinamount() + "Availableamount: " + account.getAvailableamount().multiply(floatingPriceDTO.getPrice()));

                        total++;
                        // 发送通知消息
                        MessageNotifyUtils.sendNotify(otcAd.getPublisherid(),
                                otcAd.getId(),
                                MessageNotifyEnum.BodyTemplate.ad_balance_sold_out);
                        LogUtils.info(this.getClass(), "AdvertisingSoldOutJob run success,adId : " + otcAd.getId());
                    }
                }
            }
        } catch (Exception e) {
            LogUtils.warn(this.getClass(), "AdvertisingSoldOutJobException occured " + ExceptionUtils.getStackTrace(e));
        }
        LogUtils.info(this.getClass(), "AdvertisingSoldOutJob run finish,influence ads: " + total);
    }
}
